'use strict'

const syncConfChannel = 'app:SyncConfChannel'
const {logger} = require('ee-core/log')
const {appService} = require('../service/app')
const {webContents, BrowserWindow} = require('electron')
const lodash = require('lodash')
const {autoUpdaterService} = require('../service/os/auto_updater')
const fs = require('node:fs')
const {getBaseDir} = require('ee-core/ps')
const path = require('node:path')

/**
 * 应用主页
 */
class HomeController {
    /**
     * 保存配置更新并同步到前端
     */
    async saveAndSync(args, event) {
        logger.info(HomeController.toString(), 'Call method `saveAndSync`.')
        this.#setAppConfigItems(args)
        const allWcs = webContents.getAllWebContents()
        allWcs.forEach((currentWebContents) => {
            currentWebContents.send(syncConfChannel, args)
            logger.info(HomeController.toString(), 'Dispatch the latest configuration.')
        })
    }

    /**
     * 仅仅保存应用配置更新
     */
    async onlySave(args) {
        logger.info(HomeController.toString(), 'Call method `onlySave`.')
        this.#setAppConfigItems(args)
    }

    /**
     * 保存应用配置项 (私有方法)
     */
    #setAppConfigItems(args) {
        appService.attributes = lodash.cloneDeep(args)
    }

    /**
     * 获取应用所有配置项
     */
    async getAppConfig() {
        return appService.attributes
    }

    /**
     * app检查更新
     */
    async checkForUpdate(args, event) {
        const currentWindow = BrowserWindow.fromWebContents(event.sender)
        const result = await autoUpdaterService.checkUpdate(currentWindow, args.senderName)
        //logger.info('[Auto Update] Version info', result)
        return result
    }

    /**
     * app新版本下载
     */
    async downloadLatestVersion() {
        autoUpdaterService.download()
    }

    /**
     * 查看app更新日志
     */
    async appChangeLog() {
        const changeLogPath = path.join(getBaseDir(), `CHANGELOG.${appService.appLanguageI18n}.md`)
        try {
            fs.accessSync(changeLogPath, fs.constants.F_OK | fs.constants.R_OK)
            return await fs.promises.readFile(changeLogPath, 'utf8')
        } catch (error) {
            logger.error(HomeController.toString(), error)
            return ''
        }
    }
}

HomeController.toString = () => '[class HomeController]'
module.exports = HomeController